//
//  YHY_TravelDetail_VC.m
//  Travels
//
//  Created by yanghuiyan on 16/3/8.
//  Copyright © 2016年 yanghuiyan. All rights reserved.
//

#import "YHY_TravelDetail_VC.h"
#import "YHYAFNetTool.h"
#import "Trip_daysModel.h"
#import "UIImageView+WebCache.h"
#import "NotesModel.h"
#import "TravelDetailableViewCell.h"
#import "HeaderView.h"
#import "DetailModel.h"
#import "YHY_DataBaseTool.h"
#import "MBProgressHUD.h"

@interface YHY_TravelDetail_VC ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *detailTableView;

@property (nonatomic, retain) NSMutableArray *dataSource;

@property (nonatomic, retain) Trip_daysModel *tripDaysModel;

@property (nonatomic, retain) NotesModel *notesModel;

@property (nonatomic, retain) NSMutableArray *titleArray;

@property (nonatomic, retain) HeaderView *headerView;

@property (nonatomic, retain) DetailModel *detailModel;

@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, assign) BOOL isHave;


@end

@implementation YHY_TravelDetail_VC

- (void)dealloc {
    
    _detailTableView.delegate = nil;
    _detailTableView.dataSource = nil;
    
    [_notesModel release];
    [_titleArray release];
    [_headerView release];
    [_tripDaysModel release];
    [_idNew release];
    [_detailTableView release];
    [_dataSource release];
    [super dealloc];
}


// 视图将要出现的时候 判断收藏按钮的颜色
- (void)viewWillAppear:(BOOL)animated{
    
    //设置右侧收藏按钮
    // 判断 数据库中是否存有本页数据
    self.isHave = [[YHY_DataBaseTool shareDataBase] selectDataBase:[self.idNew description]];
    
    // 若数据库中不存在 则初始化为白色星星
    if (!self.isHave) {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"16"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(favItemAction:)];
        self.navigationItem.rightBarButtonItem = rightItem;
        [rightItem release];
     
    // 若数据库中存在 则初始化为黄色的星星
    }else {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"17"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(favItemAction2:)];
        self.navigationItem.rightBarButtonItem = rightItem;
        [rightItem release];
    }

}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // 设置导航栏 透明度
    self.navigationController.navigationBar.translucent = YES;
    
    [self creatView];
    
    [self sendRequest];
    
}

#pragma mark - 创建视图
- (void)creatView {
    
    //自定义标题视图
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    titleLabel.text = @"详  情";
    titleLabel.font = [UIFont boldSystemFontOfSize:25];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    
    //设置左侧返回按钮
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"7"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];
    
    
    //创建tableView
    self.detailTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置代理人
    self.detailTableView.delegate = self;
    self.detailTableView.dataSource = self;
    // 注册重用池
    [self.detailTableView registerClass:[TravelDetailableViewCell class] forCellReuseIdentifier:@"TravelDetailableViewCellIdentifier"];
    
    [self.view addSubview:self.detailTableView];
    
    [_detailTableView release];
    
    

}

#pragma mark - 左侧按钮点击事件
- (void)leftItemAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.tabBarController.tabBar.hidden = NO;
}

#pragma mark - 右侧收藏按钮 白的星星点击事件
- (void)favItemAction:(UIBarButtonItem *)sender {
    
    //设置收藏提示框
    NSString *message = [NSString stringWithFormat:@"是否收藏"];
    NSString *title = [NSString stringWithFormat:@"提示"];
    NSString *cancel = [NSString stringWithFormat:@"取消"];
    NSString *sure = [NSString stringWithFormat:@"确认"];
    
    //创建提示框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    //确认按钮
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:sure style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 根据id值 判断 数据库中是否有此页数据
        self.isHave = [[YHY_DataBaseTool shareDataBase]selectDataBase:self.detailModel.idNew];
        
        // 如果没有此页数据
        if (self.isHave == 0) {
            
        DetailModel *detailModel = [[DetailModel alloc] init];
        detailModel.idNew = self.detailModel.idNew;
        detailModel.name = self.detailModel.name;
        detailModel.front_cover_photo_url = self.detailModel.front_cover_photo_url;
        
        // 将model插入数据库中
        [[YHY_DataBaseTool shareDataBase] insertDetailModelIntoTable:detailModel];
        [detailModel release];
}
        // 点确认 确认收藏此页
        // 再次初始化右上角button
        // 此时 星星应该为黄色
        UIBarButtonItem *favItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"17"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(favItemAction2:)];
        self.navigationItem.rightBarButtonItem = favItem;
        
        [favItem release];

    }];

    //取消按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    //添加按钮事件
    [alertController addAction:cancelAction];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
    
}
#pragma mark - 右侧收藏按钮 黄色星星
- (void)favItemAction2:(UIBarButtonItem *)sender {
    
    //设置收藏提示框
    NSString *message = [NSString stringWithFormat:@"是否取消"];
    NSString *title = [NSString stringWithFormat:@"提示"];
    NSString *cancel = [NSString stringWithFormat:@"取消"];
    NSString *sure = [NSString stringWithFormat:@"确认"];
    
    //创建提示框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    
    //确认按钮
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:sure style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    // 点是 确定取消收藏
    // 首先删除数据库里 关于此页的数据
    [[YHY_DataBaseTool shareDataBase] deleteDetailModelTable:self.detailModel.idNew];
        
   
    //删除后再次初始化 右上角的button
    //把星星变为白色
    //设置右上角收藏按钮
        UIBarButtonItem *favItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"16"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(favItemAction:)];
        self.navigationItem.rightBarButtonItem = favItem;
        [favItem release];
}];
    
    //取消按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    //添加按钮事件
    [alertController addAction:cancelAction];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
}



#pragma mark - 实现UITableViewDataSource协议方法
// 返回分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

// 返回row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    self.tripDaysModel = self.dataSource[section];
    return self.tripDaysModel.myNodes.count;

}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.notesModel = self.tripDaysModel.myNodes[indexPath.row];
    
    // 计算图片高度 调用cell类方法
    
    CGFloat imageHeight = [TravelDetailableViewCell heightWithImageWidth:self.notesModel.photo_image_width WithImageHeight:self.notesModel.photo_image_height];
    // 计算文字高度 调用cell类方法
    CGFloat textHeight = [TravelDetailableViewCell heightWithText:self.notesModel.descriptions];
    
    // 如果没有文字和图片时 高度返回0
    if (imageHeight + textHeight == 0) {
        return 0;
    }
    // 返回计算后的cell高度
    return imageHeight + 10 + textHeight;
    
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TravelDetailableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelDetailableViewCellIdentifier"];
    
    self.tripDaysModel = self.dataSource[indexPath.section];
    
    cell.notesModel = self.tripDaysModel.myNodes[indexPath.row];
    
    return cell;
    
}

// 返回section标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return self.titleArray[section];
    
}

// section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}

// 取消tableView的点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.detailTableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 数据解析
- (void)sendRequest {
    
    // 数据返回前  设置加载图标
    [self loadPic];
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
   
    NSString *string = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json", self.idNew];
        
    [YHYAFNetTool GETNetWirhUrl:string body:nil headerFile:nil response:YHYJSON Success:^(id result) {
    
    //tableView头视图
    self.detailModel = [[DetailModel alloc] initWithDataSource:result];
    self.headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200)];
    self.headerView.detailModel = self.detailModel;
    self.detailTableView.tableHeaderView = self.headerView;
            
    self.titleArray = [NSMutableArray arrayWithCapacity:0];
        
    for (NSDictionary *dic in result[@"trip_days"]) {
                
        self.tripDaysModel = [[Trip_daysModel alloc] initWithDataSource:dic];
    
        NSString *days = [NSString stringWithFormat:@"Day %@", self.tripDaysModel.day];
        // 分区标题
        [self.titleArray addObject:days];
        
        self.tripDaysModel.myNodes = [NSMutableArray arrayWithCapacity:0];
                
        for (NSDictionary *dic in self.tripDaysModel.nodes) {
                    
            NotesModel *notesModel = [[NotesModel alloc] initWithDataSource:dic];
                    
            [self.tripDaysModel.myNodes addObject:notesModel];
                    
            for (NSDictionary *otherDic in notesModel.notes) {
                        
                NotesModel *notesModel = [[NotesModel alloc] init];
                [notesModel setValuesForKeysWithDictionary:otherDic];
                        
                [self.tripDaysModel.myNodes addObject:notesModel];
                [notesModel release];
            }
            [notesModel release];
}
                
    [self.dataSource addObject:self.tripDaysModel];
                
                
        [self.tripDaysModel release];
}
     // 数据加载完成后 移除加载图标
    if (self.dataSource) {
        [self.detailTableView reloadData];
        self.HUD.hidden = YES;
}
            
    } Failure:^(NSError *error) {
            
        }];
}

#pragma mark - 数据加载图标
- (void)loadPic {
    
    //初始化
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    //设置文字
    self.HUD.labelText = @"努力加载中";
    
    //出现时间
    [self.HUD hide:YES afterDelay:5];
    
    //设置文字颜色
    self.HUD.labelColor = [UIColor whiteColor];
    
    //设置整体图标的颜色
    self.HUD.color = [UIColor grayColor];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
